#{include file="../Common/Header.html"}
<div class="layui-container fly-marginTop fly-user-main">
    #{include file="../Common/Nav.html"}
    <div class="fly-panel fly-panel-user" pad20>
        <div class="layui-tab layui-tab-brief" lay-filter="user">
            <div class="content-header">
                <i class="layui-icon">&#xe638;</i> 优惠卷管理
            </div>

            <div class="content-body">
                <div style="margin-bottom: 5px;margin-top: 15px;">
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-pink button-add"><i class="layui-icon"
                                                                                                      style="position: relative;top: -2px;">&#xe624;</i>生成优惠卷
                    </button>
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-pink button-del"><i class="layui-icon"
                                                                                                      style="position: relative;top: -2px;">&#xe640;</i>移除选中优惠卷
                    </button>

                    <button type="button" class="layui-btn layui-btn-sm layui-btn-pink button-lock"><i
                                class="layui-icon"
                                style="position: relative;top: -2px;">&#xe673;</i>锁定选中优惠卷
                    </button>

                    <button type="button" class="layui-btn layui-btn-sm layui-btn-pink button-unlock"><i
                                class="layui-icon"
                                style="position: relative;top: -2px;">&#xe672;</i>解锁选中优惠卷
                    </button>
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-pink button-export"><i
                                class="layui-icon"
                                style="position: relative;top: -2px;">&#xe67d;</i>导出筛选优惠卷
                    </button>
                </div>
                <form class="search-query"></form>

                <table id="coupon" lay-filter="coupon"></table>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        layui.use(['hex', 'form'], function () {
            let table = $("#coupon");
            let cao = layui.hex;
            let form = layui.form;
            let status = ['<span class="acg-badge acg-badge-light-red">未使用</span>', '<span class="acg-badge acg-badge-light-success">已使用</span>', '<span class="acg-badge acg-badge-light">锁定</span>'];
            var _commodity;
            let commodity = function () {
                if (!_commodity) {
                    _commodity = User.$postSync("/user/api/commodity/data", {limit: 1000, page: 1});
                }
                let dict = [];
                _commodity.forEach(item => {
                    dict.push({id: item.id, name: item.name});
                })
                return dict;
            }

            var _category;
            let category = function () {
                if (!_category) {
                    _category = User.$postSync("/user/api/category/data", {limit: 1000, page: 1});
                }
                let dict = [];
                _category.forEach(item => {
                    dict.push({id: item.id, name: item.name});
                })
                return dict;
            }




            let queryParams = null;
            table.bootstrapTable({
                url: '/user/api/coupon/data',//请求的url地址
                method: "post",//请求方式
                pageSize: 7,//每页显示的数量
                showRefresh: false,//是否显示刷新按钮
                cache: false,//是否使用缓存
                showToggle: false,//是否显示详细视图和列表视图的切换按钮
                cardView: false,
                pagination: true,//是否显示分页
                pageNumber: 1,//初始化显示第几页，默认第1页
                singleSelect: false,//复选框只能选择一条记录
                sidePagination: 'server',//分页显示方式，可以选择客户端和服务端（server|client）
                contentType: "application/x-www-form-urlencoded",//使用post请求时必须加上
                dataType: "json",//接收的数据类型
                queryParamsType: 'limit',//参数格式，发送标准的Restful类型的请求
                queryParams: function (params) {
                    params.page = (params.offset / params.limit) + 1;
                    if (queryParams) {
                        for (const key in params) {
                            queryParams[key] = params[key];
                        }
                    } else {
                        queryParams = params;
                    }
                    return queryParams;
                },
                //回调函数
                responseHandler: function (res) {
                    return {
                        "total": res.count,
                        "rows": res.data
                    }
                },
                columns: [
                    {checkbox: true}
                    , {
                        field: 'secret', title: '卷代码', formatter: function (val, item) {
                            return '<span class="acg-badge acg-badge-light">' + item.code + '</span>';
                        }
                    }
                    , {
                        field: 'mode', title: '抵扣模式', formatter: function (val, item) {
                            if (item.mode == 0) {
                                return '<span class="acg-badge acg-badge-light-success">金额</span>';
                            }

                            return '<span class="acg-badge acg-badge-light-primary">百分比</span>';
                        }
                    }
                    , {
                        field: 'money', title: '面值', formatter: function (val, item) {
                            return '<b style="color: green;">' + item.money + '</b>';
                        }
                    }
                    , {
                        field: 'commodity', title: '抵扣范围', formatter: function (val, item) {
                            if (!item.commodity && !item.category) {
                                return '<span style="color: red;">全场通用</span>';
                            }

                            if (!item.commodity && item.category) {
                                return '<span style="color: blue;">[分类]</span>' + item.category.name;
                            }

                            let race = "";

                            if (item.race) {
                                race = " (<span style='color: #20b033;'>" + item.race + "</span>)";
                            }

                            return '<span style="color: green;">[商品]</span>' + item.commodity.name + race;

                        }
                    }
                    , {
                        field: 'expire_time', title: '到期时间', formatter: function (val, item) {
                            if (!item.expire_time) {
                                return '<span class="acg-badge acg-badge-light-success">永久</span>';
                            }
                            return item.expire_time;
                        }
                    }
                    , {field: 'note', title: '备注'}
                    , {
                        field: 'status', title: '状态', formatter: function (val, item) {
                            return status[item.status];
                        }
                    }
                    , {
                        field: 'service_time', title: '使用时间', formatter: function (val, item) {
                            if (!item.service_time) {
                                return '-';
                            }
                            return item.service_time;
                        }
                    }
                    , {
                        field: 'operate',
                        title: '',
                        formatter: function (val, item) {
                            let html = '';
                            if (item.status == 0) {
                                html += '<span type="button" class="acg-badge-button acg-badge acg-badge-light-primary lock"><i class="layui-icon">&#xe673;</i> 锁定</span> ';
                            } else if (item.status == 2) {
                                html += '<span type="button" class="acg-badge-button acg-badge acg-badge-light-success unlock"><i class="layui-icon">&#xe672;</i> 解锁</span> ';
                            }
                            html += '<span type="button"  class="acg-badge-button acg-badge acg-badge-light-red del"><i class="layui-icon">&#xe640;</i> 删除</span> ';
                            return html;
                        },
                        events: {
                            'click .del': function (event, value, row, index) {
                                layer.confirm('您是否要移除该优惠卷，这是无法恢复的？', {
                                    btn: ['确认移除', '取消']
                                }, function () {
                                    $.post('/user/api/coupon/del', {list: [row.id]}, res => {
                                        layer.msg(res.msg);
                                        table.bootstrapTable('refresh', {silent: true});
                                    });
                                });
                            },
                            'click .unlock': function (event, value, row, index) {
                                $.post('/user/api/coupon/unlock', {list: [row.id]}, res => {
                                    layer.msg(res.msg);
                                    table.bootstrapTable('refresh', {silent: true});
                                });
                            },
                            'click .lock': function (event, value, row, index) {
                                $.post('/user/api/coupon/lock', {list: [row.id]}, res => {
                                    layer.msg(res.msg);
                                    table.bootstrapTable('refresh', {silent: true});
                                });
                            }
                        }
                    }
                ]
            });

            let couponUnqueId = 0;
            let modal = (values = {}) => {
                cao.popup('/user/api/coupon/save', [
                    {
                        title: "选择商品",
                        name: "commodity_id",
                        type: "select",
                        dict: commodity(),
                        placeholder: "全场通用/选择商品分类",
                        search: true,
                        change: function (value) {
                            let element = cao.popupElement("category_id", "select", couponUnqueId).parent().parent();
                            if (value == 0 || !value) {
                                element.show();
                            } else {
                                element.hide();
                            }
                        }
                    },
                    {
                        title: "商品分类",
                        name: "category_id",
                        type: "select",
                        dict: category(),
                        placeholder: "对商品分类下的所有商品进行折扣，不选则全场",
                        search: true
                    },
                    {
                        title: "商品类别",
                        name: "race",
                        type: "input",
                        placeholder: "商品类别，一般你用不着，而且不懂不要乱填哦，想用请查看说明文档"
                    },
                    {
                        title: "备注信息",
                        name: "note",
                        type: "input",
                        placeholder: "备注信息(可空)，方便查询某次生成的优惠卷"
                    },
                    {
                        title: "抵扣模式",
                        name: "mode",
                        type: "radio",
                        dict: [
                            {
                                id: 0,
                                name: "金额抵扣"
                            },
                            {
                                id: 1,
                                name: "百分比抵扣(按照商品价格)"
                            }
                        ],
                        default: 0
                    },
                    {title: "面值(金额/百分比)", name: "money", type: "input", placeholder: "金额或者百分比(小数代替范围：0~1)"},
                    {title: "过期时间", name: "expire_time", type: "date", placeholder: "过了该时间优惠卷自动失效，不填代表永不过期"},
                    {title: "可用次数", name: "life", type: "input", placeholder: "该优惠卷可以使用次数", default: "1"},
                    {title: "卷码前缀", name: "prefix", type: "input", placeholder: "请输入优惠卷代码前缀，可留空", default: "ACG"},
                    {title: "生成数量", name: "num", type: "input", placeholder: "你想生成多少张优惠卷", default: 1}
                ], res => {
                    table.bootstrapTable('refresh', {silent: true});
                    layer.open({
                        type: 1,
                        title: "优惠卷[成功:" + res.data.success + "/失败:" + res.data.error + "]",
                        area: ['420px', '660px'],
                        content: '<textarea class="layui-input" style="padding: 15px;height: 100%;">' + res.data.code + '</textarea>'
                    });
                }, values, '720px', false, "添加", unqueId => {
                    couponUnqueId = unqueId;
                });
            }

            $('.button-add').click(function () {
                modal();
            });

            $('.button-del').click(() => {
                let data = cao.listObjectToArray(table.bootstrapTable('getSelections'));
                if (data.length == 0) {
                    layer.msg("请至少勾选1个优惠卷再进行操作！");
                    return;
                }

                layer.confirm('您确定要删除已经选中的优惠卷吗？这是不可恢复的操作！', {
                    btn: ['确定', '取消']
                }, function () {
                    $.post("/user/api/coupon/del", {list: data}, res => {
                        layer.msg(res.msg);
                        table.bootstrapTable('refresh', {silent: true});
                    });
                });
            });

            $('.button-lock').click(() => {
                let data = cao.listObjectToArray(table.bootstrapTable('getSelections'));
                if (data.length == 0) {
                    layer.msg("请至少勾选1个优惠卷进行操作！");
                    return;
                }
                layer.confirm('您确定要锁定选中的优惠卷吗？', {
                    btn: ['确定', '取消']
                }, function () {
                    $.post("/user/api/coupon/lock", {list: data}, res => {
                        layer.msg(res.msg);
                        table.bootstrapTable('refresh', {silent: true});
                    });
                });
            });

            $('.button-unlock').click(() => {
                let data = cao.listObjectToArray(table.bootstrapTable('getSelections'));
                if (data.length == 0) {
                    layer.msg("请至少勾选1个优惠卷进行操作！");
                    return;
                }
                layer.confirm('您确定要解锁选中的优惠卷吗？', {
                    btn: ['确定', '取消']
                }, function () {
                    $.post("/user/api/coupon/unlock", {list: data}, res => {
                        layer.msg(res.msg);
                        table.bootstrapTable('refresh', {silent: true});
                    });
                });
            });

            $('.button-export').click(function () {
                let query = $('.search-query').serialize();
                window.open('/user/api/coupon/export?exportStatus=' + query);
            });

            cao.query('.search-query', table, [
                {title: "卷代码", name: "equal-code", type: "input", width: 150},
                {title: "备注信息", name: "equal-note", type: "input", width: 150},
                {title: "卷面值", name: "equal-money", type: "input", width: 150},
                {
                    title: "状态", name: "equal-status", type: "select", dict: [
                        {id: 0, name: "未使用"},
                        {id: 1, name: "已使用"},
                        {id: 2, name: "锁定"},
                    ], width: 150
                },
                {title: "商品ID", name: "equal-commodity_id", type: "input", width: 150}
            ], true, false);

            commodity();
            category();
        });
    });
</script>
#{include file="../Common/Footer.html"}
